//
//  HHAppUpdateVerson.m
//  ZHToolsKit
//
//  Created by chun.chen on 2018/6/19.
//

#import "HHAppUpdateVerson.h"
#import "HHAppUtils.h"

#import <HHNetworkKit/HHNetworkKit.h>
#import <BCComConfigKit/BCComConfigKit.h>
#import <BCFoundation/BCFoundationUtils.h>

#define kZHAppVersionSaveKey @"kZHAppVersionSaveKey"

@interface HHAppUpdateVerson ()
@property (nonatomic, copy, readwrite) NSString * iTunesURLStr;
@property (nonatomic, copy, readwrite) NSString * serviceVersion;
@end

@implementation HHAppUpdateVerson

///MARK: -HHPopupsProtocol
+ (NSInteger)bc_level {
    return 1;
}
+ (instancetype)bc_shareInstance {
    static HHAppUpdateVerson *kShareInstance = nil;
    static dispatch_once_t kShareInstanceOnceToken;
    dispatch_once(&kShareInstanceOnceToken, ^{
        kShareInstance = [[HHAppUpdateVerson alloc] init];
    });
    return kShareInstance;
}
- (void)hh_startWithFinished:(void (^ __nullable)(BOOL poped))finish {
    /* clientType
     100    web
     101    iOS端
     102    安卓端*/

}

+ (void)hh_start {
    [[HHAppUpdateVerson bc_shareInstance] hh_startWithFinished:nil];
}
/**
 显示更新信息
 
 @param message 信息
 @param need 是否强制更新
 @param downloadUrl 下载地址
 */
+ (void)showUpdateMessage:(NSString *)message need:(BOOL)need downloadUrl:(NSString *)downloadUrl {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:BCLOC(@"发现新版本") message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    if (!need) {
        [alertController addAction:([UIAlertAction actionWithTitle:BCLOC(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }])];
    }
    [alertController addAction:([UIAlertAction actionWithTitle:BCLOC(@"发现新版本") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.class openAppWithUrl:downloadUrl];
    }])];
    
    UIViewController * rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
    [rootViewController presentViewController:alertController animated:YES completion:nil];
}

/**
 打开下载地址
 
 @param url 下载的地址
 */
+ (void)openAppWithUrl:(NSString *)url {
    NSURL* iTunesURL = [NSURL URLWithString:url];
    if (@available(iOS 10.0, *)) {
        NSDictionary<UIApplicationOpenExternalURLOptionsKey, id> *options = [[NSDictionary<UIApplicationOpenExternalURLOptionsKey, id> alloc] init];
        [[UIApplication sharedApplication] openURL:iTunesURL options:options completionHandler:nil];
    } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        [[UIApplication sharedApplication] openURL:iTunesURL];
#pragma clang diagnostic pop
    }
}
@end
